//
//  KLSGProgramAndSpeakController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGProgramAndSpeakController.h"
#import "KLSGHotProgramCell.h"
#import "KLSGCollectAndNovelTableViewCell.h"
#import "KLSGProgramAndSpeakerModel.h"
#import "KLSGDetailProgramAndSpeakController.h"
#import "KLSGBrifAndVoiceViewController.h"
#import "KLSGPlayRadioViewController.h"

@interface KLSGProgramAndSpeakController ()
{
    NSInteger pageId;
}

@property (nonatomic, strong) NSNumber *maxPageIdString;
@property (nonatomic, strong) NSMutableArray *dataArray;
//  加载圈
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) UILabel *pullRefreshLable;

@end

@implementation KLSGProgramAndSpeakController
{
    BOOL isFlag;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.titleString;
    pageId = 1;
    [self setUpRefresh];
    [self addSetUpData];
    [self addNavigationBar];
    isFlag = YES;
    [self.navigationController setNavigationBarHidden:isFlag animated:YES];
    
    //  注册 cell
    [self.tableView registerClass:[KLSGHotProgramCell class] forCellReuseIdentifier:@"hotCell"];
    [self.tableView registerClass:[KLSGCollectAndNovelTableViewCell class] forCellReuseIdentifier:@"collectCell"];
    [self.tableView setSeparatorStyle:(UITableViewCellSeparatorStyleNone)];
}

- (void)addNavigationBar
{
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemReply) target:self action:@selector(leftReturn)];
    self.navigationItem.leftBarButtonItem = left;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
}
- (void)leftReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    isFlag = !isFlag;
    [self.navigationController setNavigationBarHidden:isFlag animated:YES];

}

//  下拉刷新
- (void)setUpRefresh
{
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
    [self.tableView headerBeginRefreshing];
    self.tableView.headerPullToRefreshText = @"下拉可以刷新";
    self.tableView.headerRefreshingText = @"正在加载";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新";
    
    [self.tableView addFooterWithTarget:self action:@selector(footerRefreshing)];
    self.tableView.footerPullToRefreshText = @"下拉可以刷新";
    self.tableView.footerRefreshingText = @"正在加载";
    self.tableView.footerReleaseToRefreshText = @"松开马上刷新";
}
- (void)headerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        pageId = 1;
        self.dataArray = nil;
        [self addSetUpData];
        [self.tableView headerEndRefreshing];
    });
}
- (void)footerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        pageId++;
        if (pageId > [self.maxPageIdString intValue]) {
        }
        [self addSetUpData];
        [self.tableView footerEndRefreshing];
    });
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KLSGProgramAndSpeakerModel *model = [[KLSGProgramAndSpeakerModel alloc] init];
    if (self.dataArray.count >= indexPath.row) {
        model = self.dataArray[indexPath.row];
    }
    if (self.section == 0 && self.index == 0) {
        KLSGHotProgramCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hotCell" forIndexPath:indexPath];

        [cell.coverImage sd_setImageWithURL:[NSURL URLWithString:model.coverSmall] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
        cell.figureLable.text = [NSString stringWithFormat:@"%d", indexPath.row + 1];
        cell.figureLable.textColor = [UIColor blackColor];
        if ([cell.figureLable.text isEqualToString:@"1"]) {
            cell.figureLable.textColor = [UIColor redColor];
        } else if ([cell.figureLable.text isEqualToString:@"2"]) {
            cell.figureLable.textColor = [UIColor orangeColor];
        } else if ([cell.figureLable.text isEqualToString:@"3"]) {
            cell.figureLable.textColor = [UIColor colorWithRed:234 / 256.0 green:49 / 256.0 blue:96 / 256.0 alpha:1];
        }
        

        [cell.coverImage sd_setImageWithURL:[NSURL URLWithString:model.coverSmall] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
        cell.figureLable.text = [NSString stringWithFormat:@"%ld", indexPath.row + 1];


        cell.titleLable.text = model.title;
        cell.nickNameLable.text = [NSString stringWithFormat:@"by %@", model.nickname];
        return cell;
    } else if ((self.section == 0 && self.index == 1) || (self.section == 0 && self.index == 2)) {
        KLSGCollectAndNovelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"collectCell" forIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        [cell.coverImage sd_setImageWithURL:[NSURL URLWithString:model.coverMiddle] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];


        cell.iconImage.image = [UIImage imageNamed:@"album_collect_count"];
        cell.figureLable.text = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
        cell.figureLable.textColor = [UIColor blackColor];
        if ([cell.figureLable.text isEqualToString:@"1"]) {
            cell.figureLable.textColor = [UIColor redColor];
        } else if ([cell.figureLable.text isEqualToString:@"2"]) {
            cell.figureLable.textColor = [UIColor orangeColor];
        } else if ([cell.figureLable.text isEqualToString:@"3"]) {
            cell.figureLable.textColor = [UIColor colorWithRed:234 / 256.0 green:49 / 256.0 blue:96 / 256.0 alpha:1];
        }
        
        cell.titleLable.text = model.title;
        cell.tagsLable.text = model.tags;
        cell.tracksCountLable.text = [NSString stringWithFormat:@"%@集", model.tracksCounts];
        return cell;
    } else {
        KLSGCollectAndNovelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"collectCell" forIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        [cell.coverImage sd_setImageWithURL:[NSURL URLWithString:model.middleLogo] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];

        [cell.coverImage sd_setImageWithURL:[NSURL URLWithString:model.middleLogo] placeholderImage:[UIImage imageNamed:@"default_anchor_avatar"]];

        NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:18] forKey:NSFontAttributeName];
        CGSize textSize = [model.nickname sizeWithAttributes:attributes];
        CGRect frame = cell.titleLable.frame;
        frame.size.width = textSize.width;
        cell.titleLable.frame = frame;
        CGRect iconFrame = cell.iconSeakerImage.frame;
        iconFrame.origin = CGPointMake(CGRectGetMaxX(cell.titleLable.frame), CGRectGetMinY(cell.titleLable.frame));
        cell.iconSeakerImage.frame = iconFrame;
        
        cell.iconSeakerImage.image = [UIImage imageNamed:@"anchor_vip"];
        cell.iconImage.image = [UIImage imageNamed:@"listicon_fan"];
        cell.figureLable.text = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
        if ([cell.figureLable.text isEqualToString:@"1"]) {
            cell.figureLable.textColor = [UIColor redColor];
        } else if ([cell.figureLable.text isEqualToString:@"2"]) {
            cell.figureLable.textColor = [UIColor orangeColor];
        } else if ([cell.figureLable.text isEqualToString:@"3"]) {
            cell.figureLable.textColor = [UIColor colorWithRed:234 / 256.0 green:49 / 256.0 blue:96 / 256.0 alpha:1];
        }
        
        cell.titleLable.text = model.nickname;
        cell.tagsLable.text = model.personDescribe;
        cell.tracksCountLable.text = [NSString stringWithFormat:@"%@", model.followersCounts];
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataArray.count < indexPath.row) {
        return;
    }
    KLSGProgramAndSpeakerModel *model = self.dataArray[indexPath.row];
    if (self.section == 0 && self.index == 0) {
        
        AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
        KLSGPlayRadioViewController *playViewController = (KLSGPlayRadioViewController *)appDelegate.playVC;
        // 根据位置得到model
        KLSGProgramAndSpeakerModel *model = self.dataArray[indexPath.row];
        // 电台标题
        playViewController.rname = model.title;
        // radioModel数组
        playViewController.radioModelArray = self.dataArray;
        // 获取当前点击下标
        playViewController.index = indexPath.row;
        // id
        playViewController.radioId = model.uid;
        playViewController.hotModel = model;
        playViewController.type = VoiceTypeHot;
        
        [self presentViewController:playViewController animated:YES completion:nil];
        
    } else if ((self.section == 0 && self.index == 1) || (self.section == 0 && self.index == 2)) {
        KLSGBrifAndVoiceViewController *BAVVC = [[KLSGBrifAndVoiceViewController alloc] init];
        BAVVC.albumIdString = [NSString stringWithFormat:@"%@", model.albumId];
        KLSGKindModel *kindModel = [[KLSGKindModel alloc] init];
        kindModel.albumCoverUrl290 = model.coverMiddle;
        kindModel.title = model.title;
        kindModel.intro = model.tags;
        kindModel.tracksCounts = model.tracksCounts;
        kindModel.albumId = model.albumId;
        BAVVC.model = kindModel;
        [self.navigationController pushViewController:BAVVC animated:YES];
        
    } else {
        KLSGDetailProgramAndSpeakController *DPASVC = [[KLSGDetailProgramAndSpeakController alloc] init];
        DPASVC.uidString = [NSString stringWithFormat:@"%@", model.uid];
        [self.navigationController pushViewController:DPASVC animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (void)addSetUpData
{
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v1/rankingList/%@?device=iPhone&key=%@&pageId=%ld&pageSize=20", self.contentTypeString,self.keyString, (long)pageId];
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    __block KLSGProgramAndSpeakController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:requset completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data != nil) {
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            self.maxPageIdString = [dictionary valueForKey:@"maxPageId"];
            
            if ([self.maxPageIdString intValue] == 1) {
                self.tableView.bounces = NO;
                [self.tableView removeFooter];
            }
            
            NSArray *array = [dictionary valueForKey:@"list"];
            for (NSDictionary *dic in array) {
                KLSGProgramAndSpeakerModel *model = [[KLSGProgramAndSpeakerModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mySelf.dataArray addObject:model];
            }
        }
        [mySelf performSelectorOnMainThread:@selector(reloadData:) withObject:mySelf.tableView waitUntilDone:NO];
    }];
    [task resume];

}
- (void)reloadData:(UITableView *)tableView
{
    [tableView reloadData];
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
